/**
 * 日期时间处理工具集
 */

/**
 * 日期格式化函数
 * @param {Date} date - 日期对象
 * @param {string} [format='yyyy-MM-dd'] - 格式字符串
 * @returns {string} 格式化后的日期字符串
 * @example
 * formatDate(new Date(2023, 8, 15), 'yyyy-MM-dd HH:mm:ss'); // '2023-09-15 00:00:00'
 */
export function formatDate(date: Date, format = 'yyyy-MM-dd'): string {
  const pad = (n: number) => n.toString().padStart(2, '0')

  return format
    .replace(/yyyy/g, date.getFullYear().toString())
    .replace(/MM/g, pad(date.getMonth() + 1))
    .replace(/dd/g, pad(date.getDate()))
    .replace(/HH/g, pad(date.getHours()))
    .replace(/mm/g, pad(date.getMinutes()))
    .replace(/ss/g, pad(date.getSeconds()))
}

/**
 * 计算日期差值
 * @param {Date} startDate - 开始日期
 * @param {Date} endDate - 结束日期
 * @returns {object} 包含不同单位的差值对象
 * @example
 * dateDiff(new Date(2023, 0, 1), new Date(2023, 0, 3));
 * // { days: 2, hours: 48, minutes: 2880, seconds: 172800 }
 */
export function dateDiff(
  startDate: Date,
  endDate: Date,
): {
  days: number
  hours: number
  minutes: number
  seconds: number
} {
  const diff = endDate.getTime() - startDate.getTime()
  return {
    days: Math.floor(diff / (1000 * 60 * 60 * 24)),
    hours: Math.floor(diff / (1000 * 60 * 60)),
    minutes: Math.floor(diff / (1000 * 60)),
    seconds: Math.floor(diff / 1000),
  }
}
